node_name=`cat config/node_name_setup.conf | grep NODE_NAME | awk '{print $2}'`
echo "Name of the machine: "$node_name""

IS_GW=`cat config/gw_setup.conf | awk ' { print $2 } ' `
GET_IFACE=`cat config/lan_setup.conf | awk ' { print $2 } ' `

echo "Generating IP address..."

if [ "$IS_GW" = "yes" ]; then

	echo "This machine is gateway"
	LAN_IP="192.168.0.1"

else

	echo "This machine is not a gateway"
	MAC_TAIL1=`ifconfig $GET_IFACE | grep HWaddr | awk '{ print $5 }' | awk ' BEGIN { FS=":" } { print $5$6 } ' `
	MAC_TAIL=${MAC_TAIL1:1}
	let MAC_DECIMAL=0x$MAC_TAIL
	RANDOM=$MAC_DECIMAL
	let MULT=RANDOM*255
	let RESULT=MULT/32767
	LAN_IP="192.168.0."$RESULT
	if [ "$RESULT" = "0" ]; then
		let MULT=RANDOM*255
	        let RESULT=MULT/32767
	        LAN_IP="192.168.0."$RESULT
	fi 
	if [ "$RESULT" = "255" ]; then
                let MULT=RANDOM*255
                let RESULT=MULT/32767
                LAN_IP="192.168.0."$RESULT
        fi 

fi

echo "LAN_IF $GET_IFACE $LAN_IP" > config/lan_setup.conf
echo "IP address assigned: $LAN_IP"

echo "Configuring host in ad hoc mode..."

iface_name=`cat config/lan_setup.conf | awk '{print $2}'`
ip_address=`cat config/lan_setup.conf | awk '{print $3}'`

atheros=`cat config/atheros.conf | grep ATHEROS | awk '{print $2}'`

if [ $atheros = "yes" ]; then
	sudo modprobe -r ath_pci
	sudo modprobe ath_pci autocreate=adhoc
	echo "Switching to Sleep mode for 5 seconds. This is required to configure Atheros cards only."
	sleep 5
	echo "Back to normal mode."
	sudo ifconfig $iface_name down
	sudo iwconfig $iface_name channel 6
	sudo ifconfig $iface_name $ip_address up
	sudo iwconfig $iface_name essid 'manifold'
else
	# The following steps are common for all cards, except Atheros.
	sudo ifconfig $iface_name down
	sudo iwconfig $iface_name mode ad-hoc 
	sudo iwconfig $iface_name channel 6
	sudo ifconfig $iface_name $ip_address up
	sudo iwconfig $iface_name essid 'manifold'
fi

echo "Configuration in ad hoc mode complete!!"
